package com.reebake.ideal.message.sms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.BooleanUtil;
import com.reebake.ideal.message.core.MessageStatusConstants;
import com.reebake.ideal.message.sms.entity.SmsSendResultDTO;
import com.reebake.ideal.message.sms.service.SmsSendService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;

import java.util.LinkedHashMap;

@Slf4j
@RequiredArgsConstructor
public class SmsSendServiceImpl implements SmsSendService {

	@Override
	public SmsSendResultDTO send(String channelId, String outTemplateId, String phoneNumbers, LinkedHashMap<String, String> data, Boolean isBatchSend, Boolean enableDelivery) {
		Assert.notBlank(phoneNumbers, "手机号码不能为空");

		SmsSendResultDTO smsSendResultDTO = new SmsSendResultDTO();
		SmsBlend smsBlend = SmsFactory.getSmsBlend(channelId);
		if(smsBlend == null) {
			log.error("通道没有配置:{}", channelId);
			smsSendResultDTO.setResponseData("通道没有配置");
			return smsSendResultDTO;
		}

		String deliveryStatus = MessageStatusConstants.READY;
		Object reason = null;
		if(BooleanUtil.isTrue(enableDelivery)) {
			try {
				SmsResponse smsResponse;
				if(BooleanUtil.isFalse(isBatchSend)) {
					smsResponse = smsBlend.sendMessage(phoneNumbers, outTemplateId, data);
				}else {
					smsResponse = smsBlend.massTexting(CollectionUtil.newArrayList(phoneNumbers.split(";")), outTemplateId, data);
				}
		        if(!smsResponse.isSuccess()) {
		        	log.error("sms send error: {}", smsResponse.getData());
		        	reason = smsResponse.getData();
					deliveryStatus = MessageStatusConstants.FAILURE;
		        }else {
					deliveryStatus = MessageStatusConstants.DELIVERED;
		        }
			}catch(Exception e) {
				reason = e.getMessage();
				log.error("sms send exception.", e);
				deliveryStatus = MessageStatusConstants.FAILURE;
			}
		}else {
			deliveryStatus = MessageStatusConstants.UNDELIVERED;
		}

		smsSendResultDTO.setDeliveryStatus(deliveryStatus);
		smsSendResultDTO.setResponseData(reason);

		return smsSendResultDTO;
	}

}
